/**
 * Summary: js脚本所能执行的函数空间
 * Version 1.0
 * Date: 13-11-20
 * Time: 下午4:40
 * Copyright: Copyright (c) 2013
 */

package com.yz.jdd.webview;

import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.GsonBuilder;
import com.tencent.smtt.sdk.WebView;


import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.yz.jdd.base.entity.Response_Base;
import com.yz.jdd.network.ApiCallback;
import com.yz.jdd.base.utils.BaseConfigs;
import com.yz.jdd.photo.compress.CompressOptions;
import com.yz.jdd.photo.model.CropOptions;
import com.yz.jdd.photo.model.TakePhotoOptions;
import com.yz.jdd.webview.net.H5Subscription;


import org.json.JSONObject;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;


public class HostJsScope {

    /**
     * 获取设备IMSI
     *
     * @param webView 浏览器
     * @return 设备IMSI
     */
    public static String getIMSI(WebView webView) {
        return ((TelephonyManager) webView.getContext().getSystemService(Context.TELEPHONY_SERVICE)).getSubscriberId();
    }

    /**
     * 获取用户系统版本大小
     *
     * @param webView 浏览器
     * @return 安卓SDK版本
     */
    public static int getOsSdk(WebView webView) {
        return Build.VERSION.SDK_INT;
    }

    //---------------- 界面切换类 ------------------

    /**
     * 结束当前窗口
     *
     * @param view 浏览器
     */
    public static void goBack(WebView view) {
        if (view.getContext() instanceof Activity) {
            ((Activity) view.getContext()).finish();
        }
    }


    //关闭webview
    public static void closeWebView(WebView webView) {
        ((Activity) webView.getContext()).finish();

    }

    /**
     * 裁剪参数配置
     * 配置输出图片的宽、高
     */
    public static CropOptions configCropOptions(int outputWidth, int outputHeight) {
        CropOptions.Builder cropBuilder = new CropOptions.Builder();
        return cropBuilder.setOutputX(outputWidth).setAspectY(outputHeight).create();
    }

    /**
     * @param maxSize 容量
     * @param unit    单位kb
     * @return
     */
    public static CompressOptions configCompressOptions(int maxSize, String unit) {
        CompressOptions.Builder compressBuilder = new CompressOptions.Builder();
        if ("k".equalsIgnoreCase(unit)) {
            return compressBuilder.setMaxSize(maxSize).create();
        } else if ("m".equalsIgnoreCase(unit)) {
            return compressBuilder.setMaxSize(maxSize / 1024).create();
        } else {
            return compressBuilder.setMaxSize(maxSize).create();
        }
    }

    /**
     * 拍照参数配置
     */
    public static TakePhotoOptions configTakePhotoOptions() {
        TakePhotoOptions.Builder takePhotoBuilder = new TakePhotoOptions.Builder();
        return takePhotoBuilder.setCorrectImage(true).create();
    }

    //回调函数
    public void resultCallBack(final WebView webView, final String apiName, String result, final CallBackFunction function) {
        Log.i("lkf", "callback param:" + result);
        try {
            JsonObject jsonObject = Json2JsonObject(result);
            String data = jsonObject.get("data").getAsString();
            Map<String, Object> headers=new HashMap<String,Object>();
            if(jsonObject.get("header")!=null&&!"".equals(jsonObject.get("header"))){
                headers= toMap(jsonObject.get("header").getAsJsonObject());
            }

            String type = jsonObject.get("type").getAsString();
            String url = jsonObject.get("url").getAsString();
            if (TextUtils.isEmpty(url))
                return;
            if ("get".equalsIgnoreCase(type)) {//get请求
                H5Subscription.h5GetSubscription(headers, url, Json2Map(data), new ApiCallback() {
                    @Override
                    public void onSuccess(Response_Base response_baseModel) {
                        h5PostCallBack(webView, apiName, response_baseModel, function);
                    }

                    @Override
                    public void onNeedLogin(String msg) {
                        //IntentHandler.startLoginActivity(webView.getContext());

                    }

                    @Override
                    public void onFail(Response_Base response_baseModel) {
                        h5PostCallBack(webView, apiName, response_baseModel, function);
                    }
                });

            } else if ("post".equalsIgnoreCase(type)) {
                H5Subscription.h5PostSubscription(headers, url, Json2JsonObject(data), new ApiCallback() {
                    @Override
                    public void onSuccess(Response_Base response_baseModel) {
//                        Log.e("lkf","----------------"+response_baseModel.toString());
                        h5PostCallBack(webView, apiName, response_baseModel, function);
                    }

                    @Override
                    public void onNeedLogin(String msg) {
                        //IntentHandler.startLoginActivity(webView.getContext());
                    }

                    @Override
                    public void onFail(Response_Base response_baseModel) {
                        h5PostCallBack(webView, apiName, response_baseModel, function);
                    }
                });
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public static void h5PostLocalCallBack(final WebView webView, final String code, final String msg, final boolean success, final String apiName, final Object response_base, final CallBackFunction function) {
        ((Activity) webView.getContext()).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                H5PostCallBack h5back = new H5PostCallBack();
                h5back.setCmd(apiName);
                //拼接result参数
                if (response_base == null) {
                    h5back.setCode(code);
                    h5back.setMsg(msg);
                    h5back.setSuccess(success);
                } else {
                    h5back.setCode(code);
                    h5back.setMsg(msg);
                    h5back.setSuccess(success);
                   // h5back.setResultObject(response_base);
                    if (response_base != null) {
                        try {
                            Gson gson = new Gson();
                            String str = gson.toJson(response_base);
                            JsonElement jsonElement = new JsonParser().parse(str);
                            h5back.setResultObject(jsonElement);
                        } catch (Exception e) {

                        }
                    }
                }
                if (function != null)
                    function.onCallBack(h5back.toJSON());
//                Log.i("lkf", "....." + h5back.toJSON());
            }
        });

    }

    public static void h5PostCallBack(final WebView webView, final String apiName, final Response_Base response_base, final CallBackFunction function) {
        ((Activity) webView.getContext()).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                H5PostCallBack h5back = new H5PostCallBack();
                h5back.setCmd(apiName);
                //拼接result参数
                if (response_base == null) {
                    h5back.setCode("-1");
                    h5back.setMsg("请求失败");
                    h5back.setSuccess(false);
                } else {
                    h5back.setCode("0");
                    h5back.setMsg("请求成功");
                    h5back.setSuccess(true);
                    if (response_base != null) {
                        try {
                            Gson gson = new GsonBuilder().serializeNulls()
                            //.excludeFieldsWithoutExposeAnnotation()
                                    .disableHtmlEscaping()
                                    .create();
                            String str = gson.toJson(response_base);
//                            JsonElement jsonElement = new JsonParser().parse(str);
//                            String resultObjectStr=jsonElement.toString();
//                            Log.e("lkf","resultObjectStr=="+resultObjectStr);
//                            Log.e("lkf","response_base==="+str);
//                            h5back.setResultObject(str);
                            h5back.setResultObject(response_base);
                        } catch (Exception e) {

                        }
                    } else {
                        h5back.setResultObject(null);
                    }
                }
                if (function != null){
                    String callBackStr=h5back.toJSON();
                    function.onCallBack(callBackStr);

                    if (BaseConfigs.DEBUG)
                        Log.i("lkf", "...callBackStr===" +callBackStr);

                }

            }
        });

    }


    //json字符串转换为JsonObject
    public static JsonObject Json2JsonObject(String jsonStr) {
        JsonObject returnData = null;
        try {
            returnData = new JsonParser().parse(jsonStr).getAsJsonObject();
        } catch (Exception e) {
            return null;
        }

        return returnData;
    }

    //json字符串转换为Map<String,Object>
    public static Map<String, Object> Json2Map(String jsonStr) {
        return toMap(Json2JsonObject(jsonStr));
    }

    /**
     * 将JSONObjec对象转换成Map-List集合
     *
     * @param json
     * @return
     */
    public static Map<String, Object> toMap(JsonObject json) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            Set<Map.Entry<String, JsonElement>> entrySet = json.entrySet();
            for (Iterator<Map.Entry<String, JsonElement>> iter = entrySet.iterator(); iter.hasNext(); ) {
                Map.Entry<String, JsonElement> entry = iter.next();
                String key = entry.getKey();
                Object value = entry.getValue();
                if (value instanceof JsonArray)
                    map.put((String) key, toList((JsonArray) value));
                else if (value instanceof JsonObject)
                    map.put((String) key, toMap((JsonObject) value));
                else
                    map.put((String) key, value);
            }
        } catch (Exception e) {
        }
        return map;
    }

    /**
     * 将JSONArray对象转换成List集合
     *
     * @param json
     * @return
     */
    public static List<Object> toList(JsonArray json) {
        List<Object> list = new ArrayList<Object>();
        try {
            for (int i = 0; i < json.size(); i++) {
                Object value = json.get(i);
                if (value instanceof JsonArray) {
                    list.add(toList((JsonArray) value));
                } else if (value instanceof JsonObject) {
                    list.add(toMap((JsonObject) value));
                } else {
                    list.add(value);
                }
            }
        } catch (Exception e) {

        }
        return list;
    }
}